//
//  ByUISceneVC.m
//  laserdevice_ios
//
//  Created by pro on 16/11/24.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByUISceneVC.h"

// 数据处理
#import "ByBlueToothDataOperationModel.h"
#import "ByBlueToothHandleModel.h"

// model
#import "ByShapeModel.h"

// vc
#import "ByBlueToothListVC.h"           // 蓝牙列表
#import "ByUISceneHistoryVC.h"          // 历史场景

// view
#import "ByUISceneShapeMakeView.h"      // 图形创建视图
#import "ByUISceneOperateView.h"        // 场景操作视图

#import "ByShapeBaseView.h"             // 图形视图

#import "ByUISceneSaveView.h"           // 保存视图

@interface ByUISceneVC () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) ByShapeBaseView *contentView;

@property (nonatomic, strong) NSMutableString *dataString;


// 拖动数据所有类 11.4修改
// 距离显示移动视图
@property (nonatomic, strong) UILabel *moveView;
// 现在显示的所有models
@property (nonatomic, copy) NSArray *allModels;
// 现在显示的所有labels
@property (nonatomic, copy) NSArray *allLabels;
// 现在显示的所有frames
@property (nonatomic, copy) NSArray *allFrames;
// 高亮的线段对应的model
@property (nonatomic, strong) ByShapeModel *highModel;


@end


@implementation ByUISceneVC
{
    bool _needMakeAMeasture;    // 是否需要一次测量，给图形拍照和选择图片不需要测量
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self addLeftBackBarButtonItem];
    
    [self createNaviFunctionItems];     // 创建导航栏上的功能按钮
    [self createShapeMakeView];         // 创建图形创建视图
    [self createOperateView];           // 创建场景操作视图
    [self createContentView];           // 创建内容视图
    
    
    _needMakeAMeasture = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.ljwKeyboardHandler stopHandling];
    
    [self operateDistance];
    
}
- (void)testBluetooth {
    
//    BabyBluetooth *baby = [BabyBluetooth shareBabyBluetooth];
//
//    //设置设备连接成功的委托,同一个baby对象，使用不同的channel切换委托回调
//    [baby setBlockOnConnectedAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral) {
//        NSLog(@"%@", [NSString stringWithFormat:@"设备：%@--连接成功",peripheral.name]);
//    }];
//    
//    //设置设备连接失败的委托
//    [baby setBlockOnFailToConnectAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
//        NSLog(@"设备：%@--连接失败",peripheral.name);
//        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"设备：%@--连接失败",peripheral.name]];
//    }];
//    
//    //设置设备断开连接的委托
//    [baby setBlockOnDisconnectAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
//        NSLog(@"设备：%@--断开连接",peripheral.name);
//        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"设备：%@--断开失败",peripheral.name]];
//    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [[ByBlueToothHandleModel shareInstance] closeHistoryMeasure];
}

#pragma mark - 处理数据
- (void)operateDistance {
    
    self.dataString = [[NSMutableString alloc] init];
    
    [[ByBlueToothHandleModel shareInstance] startDistanceMeasure:^(NSString *dataHex) {
        
        // 接收到应答信号则不做处理
        if ([dataHex isEqualToString:@"F0"] || [dataHex isEqualToString:@"f0"]) {
            return;
        }
        // 接收到的传递产品信息的数据，则不做处理
        if (dataHex.length == 18 * 2 && [[dataHex substringWithRange:NSMakeRange(28, 4)] isEqualToString:@"5648"]) {
            return;
        }
        
        [self.dataString appendString:dataHex];
        // 接收到以FA为后缀的，说明数据接收完成
        NSLog(@"%@", self.dataString);
        if ([self.dataString hasSuffix:@"FA"] || [self.dataString hasSuffix:@"fa"]) {
            
            NSString *str = [[self.dataString componentsSeparatedByString:@"fa"] firstObject];
            self.dataString = [NSMutableString stringWithFormat:@"%@fa", str];
            
            ByUISceneOperateView *operateView = [self.view viewWithTag:10];

            // 实用数据
            NSString *distance = [ByBlueToothDataOperationModel displayDistanceOperation:self.dataString];
            
            // 数据可用，则添加到数据字典
            if (distance) {
                [operateView setDistance:distance];
            }
            
            // 把可变数据字符串清空
            self.dataString = [[NSMutableString alloc] init];
        }

    } withOneMeasure:_needMakeAMeasture];

}

#pragma mark - create view
// 创建导航栏上的功能按钮
- (void)createNaviFunctionItems {
    
    // 基底视图
    UIView *basalView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.85, 44)];

    NSArray *texts = @[STRING(@"xiangjiqujing"),
                       STRING(@"tupianqujing"),
                       STRING(@"lishichangjing"),
                       STRING(@"baocunchangjing"),];
    NSArray *images = @[@"scene_xiangji",
                        @"scene_tupian",
                        @"scene_lishi",
                        @"scene_baocun"];
    // 循环创建
    CGFloat margin = 1;
    
    for (int i = 0; i < texts.count; i ++) {
        CGFloat width = basalView.width / texts.count;
        CGFloat height = basalView.height;
        CGFloat x = i * width;
        CGFloat y = 0;
        UIControl *mixView = [[UIControl alloc] init];
        mixView.frame = CGRectMake(x, y, width, height);
        [mixView addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        [basalView addSubview:mixView];
        mixView.tag = i;
        
        // 图片
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
        imgView.image = [UIImage imageNamed:images[i]];
        
        // 文字
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 16)];
        label.adjustsFontSizeToFitWidth = YES;
        label.font = FONT(13);
        label.text = texts[i];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        
        [mixView addSubview:imgView];
        [mixView addSubview:label];
        
        // 设置位置
        CGFloat remainY = mixView.height - imgView.height - label.height - margin;
        imgView.top = remainY / 2;
        imgView.x = mixView.width / 2;
        label.top = imgView.bottom + margin;
        
    }
    
    [self addCustomItemviews:@[basalView] position:ByNavigationItemPositionModeRight];

}
// 创建图形创建视图
- (void)createShapeMakeView {
    
    ByUISceneShapeMakeView *shapeMakeView = [[ByUISceneShapeMakeView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 60)];
    shapeMakeView.backgroundColor = rgba(29, 29, 29, 1);
    [self.view addSubview:shapeMakeView];
    shapeMakeView.bottom = SCREEN_HEIGHT - 64;
    
    // 点击事件
    [shapeMakeView setDidSelectShape:^(NSInteger index) {
        
        [self.contentView addShapeWithMode:index];
    }];
}
// 创建场景操作视图
- (void)createOperateView {
    
    ByUISceneOperateView *operateView = [[ByUISceneOperateView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width / 10)];
    operateView.backgroundColor = rgba(29, 29, 29, 1);
    [self.view addSubview:operateView];
    operateView.tag = 10;
    
    // 点击事件
    [operateView setDidSelectOperation:^(NSInteger index) {
        
        if (index == 0) {   // 撤销
            
            [self.contentView revoke];
        }
        if (index == 1) {   // 重做
            
            [self.contentView reset];
        }
        if (index == 2) {   // 删除
            
            [self.contentView deleteShape];
        }
    
    }];
    
    // 长按拖动代理
    [operateView setMoveingDistance:^(UIPanGestureRecognizer *sender, CGFloat distance) {
        
        int unit = [ByCommonCache getSystemUnit].intValue; // 单位（英寸保留两位小数）
        
        if (sender.state == UIGestureRecognizerStateBegan) {
            _moveView = [[UILabel alloc] initWithFrame:sender.view.bounds];
            _moveView.font = FONT(13);
            if (unit == 2) {
                _moveView.text = [NSString stringWithFormat:@"%.2lf", distance];
            } else {
                _moveView.text = [NSString stringWithFormat:@"%.3lf", distance];
            }
            _moveView.textColor = [UIColor blackColor];
            _moveView.textAlignment = NSTextAlignmentCenter;

            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            if (![window.subviews containsObject:_moveView]) {
                [window addSubview:_moveView];
            }
            CGPoint point = [sender locationInView:window];
            _moveView.center = point;
            
            // 获得到所有显示的图形
            self.allModels = _contentView.models;
            // 遍历所有图形获得labels数组
            NSMutableArray *allLabels = [[NSMutableArray alloc] init];
            NSMutableArray *allFrames = [[NSMutableArray alloc] init];
            for (ByShapeModel *model in self.allModels) {
                for (UILabel *label in model.labels) {
                    
                    CGRect frame = [self.contentView convertRect:label.frame toView:window];
                    CGFloat width = frame.size.width;
                    CGFloat height = frame.size.height;
                    CGFloat x = frame.origin.x - 0.5 * width;
                    CGFloat y = frame.origin.y - 0.5 * height;
                    // 拓展其触摸范围
                    frame = CGRectMake(x, y, width * 2, height * 2);
                    
                    [allFrames addObject:NSStringFromCGRect(frame)];
                    [allLabels addObject:label];
                }
            }
            self.allLabels = allLabels.copy;
            self.allFrames = allFrames.copy;

        } else if (sender.state == UIGestureRecognizerStateChanged) {
            
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            CGPoint point = [sender locationInView:window];
            _moveView.center = point;

            // 遍历所有可触摸范围，寻找第一个可触摸范围
            for (NSString *frameStr in self.allFrames) {
                
                // 如果触摸点在触摸范围内，就设置高亮model
                if (CGRectContainsPoint(CGRectFromString(frameStr), point)) {

                    NSInteger index = [self.allFrames indexOfObject:frameStr];

                    UILabel *highLabel = [self.allLabels objectAtIndex:index];
                    
                    for (ByShapeModel *model in self.allModels) {
                        if ([model.labels containsObject:highLabel]) {
                            
                            [model setHighLightLabel:highLabel];
                            // 设置高亮model，用于在手指松开后重回
                            _highModel = model;
                        } else {
                            model.highLightLabel = nil;
                        }
                    }
                    
                    _contentView.models = [[NSMutableArray alloc] initWithArray:self.allModels];
                    
                    break;
                }
                // 否则高亮model设为nil
                else {
                    
                    _highModel = nil;
                    
                    for (ByShapeModel *model in self.allModels) {
                        model.highLightLabel = nil;
                    }
                    
                    _contentView.models = [[NSMutableArray alloc] initWithArray:self.allModels];
                }

            }
            
            [_contentView updatePaths];

            
        } else if (sender.state == UIGestureRecognizerStateEnded) {
            
            [_moveView removeFromSuperview];
            _moveView = nil;
            
            if (_highModel != nil) {
                
                NSString *distanceStr = nil;
                if (unit == 2) {
                    distanceStr = [NSString stringWithFormat:@"%.2lf", distance];
                } else {
                    distanceStr = [NSString stringWithFormat:@"%.3lf", distance];
                }
                [_highModel setHighLightLabel:_highModel.highLightLabel distance:distanceStr];
            }
            [_contentView updatePaths];

            // 全部不显示高亮
            for (ByShapeModel *model in self.allModels) {
                model.highLightLabel = nil;
            }
            
            _contentView.models = [[NSMutableArray alloc] initWithArray:self.allModels];
            [_contentView updatePaths];
        } else if (sender.state == UIGestureRecognizerStateCancelled) {
            
            [_moveView removeFromSuperview];
            _moveView = nil;
            
            if (_highModel != nil) {
                
                NSString *distanceStr = nil;
                if (unit == 2) {
                    distanceStr = [NSString stringWithFormat:@"%.2lf", distance];
                } else {
                    distanceStr = [NSString stringWithFormat:@"%.3lf", distance];
                }
                [_highModel setHighLightLabel:_highModel.highLightLabel distance:distanceStr];
            }
            [_contentView updatePaths];
            
            // 全部不显示高亮
            for (ByShapeModel *model in self.allModels) {
                model.highLightLabel = nil;
            }
            
            _contentView.models = [[NSMutableArray alloc] initWithArray:self.allModels];
            [_contentView updatePaths];
        }
    }];
}
// 创建内容视图
- (void)createContentView {
    
    self.contentView = [[ByShapeBaseView alloc] initWithFrame:CGRectMake(0, self.view.width / 10, self.view.width, SCREEN_HEIGHT - 64 - 60 - self.view.width / 10)];
    self.contentView.selectPictureBlock = ^ {
        _needMakeAMeasture = NO;
    };
    [self.view addSubview:self.contentView];
}



#pragma mark - 点击事件
- (void)leftItemsAction:(NSInteger)leftIndex {
    
    
    [UIAlertView showWithTitle:STRING(@"tuichu") message:STRING(@"tuichuqianshifoubaocun") cancelButtonTitle:STRING(@"zhijietuichu") otherButtonTitles:@[STRING(@"xianbaocun")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [super leftItemsAction:leftIndex];
            return;
        } else {
            [self performSelector:@selector(delayAction) withObject:nil afterDelay:0.5];
        }
    }];
    
    
}
- (void)delayAction {
    
    ByUISceneSaveView *saveView = [[ByUISceneSaveView alloc] initWithFunctions:@[STRING(@"baocunshezhiwenjian"),STRING(@"daochuJPG"),STRING(@"daochuPDF")]];
    [saveView show];
    saveView.backAction = ^ (NSInteger tag) {
        
        if (tag == 0) {
            [self saveToHistoryFile];
        }
        if (tag == 1) {
            [self exportToJPG];
        }
        if (tag == 2) {
            [self exportToPDF];
        }
    };
}
- (void)tapAction:(UIControl *)sender {
    
    switch (sender.tag) {
        case 0:     // 拍照
        {
            _needMakeAMeasture = NO;
            [self getPhotoFromCamera];
            break;
        }
        case 1:     // 图片
        {
            _needMakeAMeasture = NO;
            [self getPhotoFromAlbum];
            break;
        }
        case 2:     // 历史场景
        {
            _needMakeAMeasture = YES;
            ByUISceneHistoryVC *vc = [[ByUISceneHistoryVC alloc] init];
            vc.backAction = ^ (NSDictionary *jsonDic) {
                
                [self.contentView removeFromSuperview];
                self.contentView = nil;
                
                self.contentView = [[ByShapeBaseView alloc] initWithFrame:CGRectMake(0, self.view.width / 10, self.view.width, (SCREEN_HEIGHT - 64 - 60 - self.view.width / 10)) jsonDic:jsonDic];
                [self.view addSubview:self.contentView];
            };
            
            [self by_normalPush:vc hasNavi:YES];
            break;
        }
        case 3:     // 保存场景
        {
            _needMakeAMeasture = NO;
            ByUISceneSaveView *saveView = [[ByUISceneSaveView alloc] initWithFunctions:@[STRING(@"baocunshezhiwenjian"),STRING(@"daochuJPG"),STRING(@"daochuPDF")]];
            [saveView show];
            saveView.backAction = ^ (NSInteger tag) {
              
                if (tag == 0) {
                    [self saveToHistoryFile];
                }
                if (tag == 1) {
                    [self exportToJPG];
                }
                if (tag == 2) {
                    [self exportToPDF];
                }
            };
            return;
            
            
            break;
        }
        default:
            break;
    }
    
}

// 保存成app内的文件
- (void)saveToHistoryFile {
    
    [UIAlertView showWithTitle:nil
                       message:STRING(@"weichangjingmingming")
                         style:UIAlertViewStylePlainTextInput
                   defaultText:[NSDate getCurrentDateForStringFormatWithFormatter:nil]
             cancelButtonTitle:@"cancel"
             otherButtonTitles:@[@"ok"]
                      tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        UITextField *tf = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            
            NSMutableDictionary *tempDic = self.contentView.saveDictionary;
            [tempDic setObject:tf.text forKey:@"name"];
            [tempDic setObject:@"LD" forKey:@"source_type"];
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tempDic.copy options:NSJSONWritingPrettyPrinted error:nil];
            
            UIImageView *baseImgView = [self.contentView viewWithTag:111];
            
            [ByFileManager saveSceneWithName:tf.text
                                     bgImage:baseImgView.image
                                 shapeImages:self.contentView.shapeImages
                                        json:jsonData
                                     existed:^{
                                         
                                         NSLog(@"文件夹已经存在");
                                     }
                                     failure:^(NSError *error) {
                                         
                                         NSLog(@"保存失败");
                                     }];
        }
    }];
}

- (void)exportToJPG {
    
    CGSize size = self.contentView.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [self.contentView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {

}

- (void)exportToPDF {
    
    CGSize size = self.contentView.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [self.contentView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    [UIAlertView showWithTitle:nil
                       message:STRING(@"weichangjingmingming")
                         style:UIAlertViewStylePlainTextInput
                   defaultText:[NSDate getCurrentDateForStringFormatWithFormatter:nil]
             cancelButtonTitle:STRING(@"quxiao")
             otherButtonTitles:@[STRING(@"queding")]
                      tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        UITextField *tf = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            
            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
            [tempDic setObject:tf.text forKey:@"name"];
            [tempDic setObject:@"PDF" forKey:@"source_type"];
            [tempDic setObject:[NSDate getCurrentDateForStringFormatWithFormatter:nil] forKey:@"create_time"];
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tempDic.copy options:NSJSONWritingPrettyPrinted error:nil];
            
            [ByFileManager saveSceneForPDFWithName:tf.text
                                          image:image
                                           size:CGSizeMake(self.contentView.width, self.contentView.height)
                                           json:jsonData];
        }
    }];

    

}

#pragma mark - 拍照
- (void)getPhotoFromAlbum {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [UIAlertView showWithTitle:nil message:STRING(@"xiangcebukeyong")cancelButtonTitle:STRING(@"queding") otherButtonTitles:nil tapBlock:nil];
        return;
    }
    [self gotoPickerController:sourceType];
}
- (void)getPhotoFromCamera {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [UIAlertView showWithTitle:nil message:STRING(@"xiangjibukeyong") cancelButtonTitle:STRING(@"queding") otherButtonTitles:nil tapBlock:nil];
        return;
    }
    [self gotoPickerController:sourceType];
}
- (void)gotoPickerController:(UIImagePickerControllerSourceType)sourceType {

    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    pickerController.sourceType = sourceType;
    pickerController.title = STRING(@"xuanzetupian");
    [pickerController.navigationBar setTintColor:CJ_THEME_COLOR];
    [self presentViewController:pickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:^{
        self.contentView.baseImg = image;
    }];
}





@end
